/**
 * 增强版仪表盘组件
 * 展示如何使用新的前端架构组件
 */

import { ComponentBase } from '../common/component-base.js';
import { apiClient } from '../common/api-client.js';
import { stateManager } from '../common/state-manager.js';

export class EnhancedDashboard extends ComponentBase {
    constructor(container, options = {}) {
        super(container, options);
        
        // 初始化图表
        this.charts = new Map();
        
        // 订阅状态变化
        this.setupStateSubscriptions();
    }

    /**
     * 获取HTML模板
     */
    getTemplate() {
        return `
            <div class="dashboard">
                <div class="dashboard-header">
                    <h1>仪表盘总览</h1>
                    <div class="dashboard-controls">
                        <div class="time-range-selector">
                            <label for="timeRange">时间范围：</label>
                            <select id="timeRange" class="form-control">
                                <option value="today">今天</option>
                                <option value="week" selected>本周</option>
                                <option value="month">本月</option>
                                <option value="year">本年</option>
                            </select>
                        </div>
                        <div class="refresh-button">
                            <button id="refreshBtn" class="btn btn-primary">
                                <i class="fas fa-sync-alt"></i> 刷新数据
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="dashboard-content">
                    <!-- 指标卡片 -->
                    <div class="metrics-cards">
                        <div class="metric-card">
                            <div class="metric-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <div class="metric-content">
                                <h3>总访问量</h3>
                                <div class="metric-value" id="totalVisits">-</div>
                                <div class="metric-change" id="visitsChange">-</div>
                            </div>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-icon">
                                <i class="fas fa-user-check"></i>
                            </div>
                            <div class="metric-content">
                                <h3>独立访客</h3>
                                <div class="metric-value" id="uniqueVisitors">-</div>
                                <div class="metric-change" id="visitorsChange">-</div>
                            </div>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-icon">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <div class="metric-content">
                                <h3>转化率</h3>
                                <div class="metric-value" id="conversionRate">-</div>
                                <div class="metric-change" id="conversionChange">-</div>
                            </div>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-icon">
                                <i class="fas fa-clock"></i>
                            </div>
                            <div class="metric-content">
                                <h3>平均停留时间</h3>
                                <div class="metric-value" id="avgDuration">-</div>
                                <div class="metric-change" id="durationChange">-</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图表区域 -->
                    <div class="charts-container">
                        <div class="chart-container">
                            <div class="chart-header">
                                <h3>访问趋势</h3>
                                <div class="chart-controls">
                                    <button class="btn btn-sm chart-type-btn active" data-chart="line">
                                        <i class="fas fa-chart-line"></i>
                                    </button>
                                    <button class="btn btn-sm chart-type-btn" data-chart="bar">
                                        <i class="fas fa-chart-bar"></i>
                                    </button>
                                </div>
                            </div>
                            <div id="visitsChart" class="chart"></div>
                        </div>
                        
                        <div class="chart-container">
                            <div class="chart-header">
                                <h3>页面分布</h3>
                                <div class="chart-controls">
                                    <button class="btn btn-sm chart-type-btn active" data-chart="pie">
                                        <i class="fas fa-chart-pie"></i>
                                    </button>
                                    <button class="btn btn-sm chart-type-btn" data-chart="donut">
                                        <i class="fas fa-circle-notch"></i>
                                    </button>
                                </div>
                            </div>
                            <div id="pagesChart" class="chart"></div>
                        </div>
                    </div>
                    
                    <!-- 实时活动 -->
                    <div class="activity-container">
                        <div class="activity-header">
                            <h3>实时活动</h3>
                            <div class="activity-status">
                                <span class="status-indicator online"></span>
                                <span>实时更新中</span>
                            </div>
                        </div>
                        <div class="activity-list" id="activityList">
                            <div class="activity-item">
                                <div class="activity-icon">
                                    <i class="fas fa-user"></i>
                                </div>
                                <div class="activity-content">
                                    <div class="activity-text">新用户注册</div>
                                    <div class="activity-time">刚刚</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 渲染后调用
     */
    onRendered() {
        // 初始化图表
        this.initCharts();
        
        // 加载初始数据
        this.loadData();
        
        // 启动实时更新
        this.startRealTimeUpdates();
    }

    /**
     * 组件挂载后调用
     */
    onMounted() {
        console.log('Dashboard component mounted');
    }

    /**
     * 组件销毁前调用
     */
    onBeforeDestroy() {
        // 停止实时更新
        this.stopRealTimeUpdates();
        
        // 销毁图表
        this.destroyCharts();
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 时间范围选择
        this.addEventListener('#timeRange', 'change', (e) => {
            this.loadData();
        });
        
        // 刷新按钮
        this.addEventListener('#refreshBtn', 'click', () => {
            this.refreshData();
        });
        
        // 图表类型切换
        this.findAll('.chart-type-btn').forEach(btn => {
            this.addEventListener(btn, 'click', (e) => {
                const chartType = e.currentTarget.dataset.chart;
                const container = e.currentTarget.closest('.chart-container');
                const chartId = container.querySelector('.chart').id;
                
                // 更新按钮状态
                container.querySelectorAll('.chart-type-btn').forEach(b => {
                    b.classList.remove('active');
                });
                e.currentTarget.classList.add('active');
                
                // 切换图表类型
                this.switchChartType(chartId, chartType);
            });
        });
    }

    /**
     * 设置状态订阅
     */
    setupStateSubscriptions() {
        // 订阅用户状态变化
        this.subscribe('user', (user) => {
            if (user) {
                console.log(`Dashboard updated for user: ${user.username}`);
            }
        });
        
        // 订阅通知状态变化
        this.subscribe('notifications', (notifications) => {
            if (notifications.length > 0) {
                console.log(`New notifications: ${notifications.length}`);
            }
        });
    }

    /**
     * 初始化图表
     */
    initCharts() {
        // 检查ECharts是否加载
        if (typeof echarts === 'undefined') {
            console.error('ECharts library not loaded');
            return;
        }
        
        // 初始化访问趋势图表
        const visitsChart = echarts.init(this.find('#visitsChart'));
        this.charts.set('visits', visitsChart);
        
        // 初始化页面分布图表
        const pagesChart = echarts.init(this.find('#pagesChart'));
        this.charts.set('pages', pagesChart);
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.charts.forEach(chart => chart.resize());
        });
    }

    /**
     * 加载数据
     */
    async loadData() {
        try {
            // 设置加载状态
            this.setState({ loading: true });
            
            // 获取时间范围
            const timeRange = this.find('#timeRange').value;
            
            // 并行加载数据
            const [metricsData, visitsData, pagesData] = await Promise.all([
                this.loadMetrics(timeRange),
                this.loadVisitsData(timeRange),
                this.loadPagesData(timeRange)
            ]);
            
            // 更新指标卡片
            this.updateMetrics(metricsData);
            
            // 更新图表
            this.updateVisitsChart(visitsData);
            this.updatePagesChart(pagesData);
            
            // 更新状态
            this.setState({ 
                loading: false,
                lastUpdated: new Date()
            });
            
        } catch (error) {
            console.error('Failed to load dashboard data:', error);
            
            // 显示错误消息
            this.showError('加载数据失败，请稍后重试');
            
            // 更新状态
            this.setState({ loading: false });
        }
    }

    /**
     * 加载指标数据
     */
    async loadMetrics(timeRange) {
        const response = await apiClient.get('/analytics/metrics', { timeRange });
        return response.data;
    }

    /**
     * 加载访问数据
     */
    async loadVisitsData(timeRange) {
        const response = await apiClient.get('/analytics/visits', { timeRange });
        return response.data;
    }

    /**
     * 加载页面数据
     */
    async loadPagesData(timeRange) {
        const response = await apiClient.get('/analytics/pages', { timeRange });
        return response.data;
    }

    /**
     * 更新指标卡片
     */
    updateMetrics(data) {
        // 更新总访问量
        this.find('#totalVisits').textContent = data.totalVisits.toLocaleString();
        this.find('#visitsChange').textContent = this.formatChange(data.visitsChange);
        this.updateChangeIndicator(this.find('#visitsChange'), data.visitsChange);
        
        // 更新独立访客
        this.find('#uniqueVisitors').textContent = data.uniqueVisitors.toLocaleString();
        this.find('#visitorsChange').textContent = this.formatChange(data.visitorsChange);
        this.updateChangeIndicator(this.find('#visitorsChange'), data.visitorsChange);
        
        // 更新转化率
        this.find('#conversionRate').textContent = `${data.conversionRate}%`;
        this.find('#conversionChange').textContent = this.formatChange(data.conversionChange);
        this.updateChangeIndicator(this.find('#conversionChange'), data.conversionChange);
        
        // 更新平均停留时间
        this.find('#avgDuration').textContent = this.formatDuration(data.avgDuration);
        this.find('#durationChange').textContent = this.formatChange(data.durationChange);
        this.updateChangeIndicator(this.find('#durationChange'), data.durationChange);
    }

    /**
     * 更新访问趋势图表
     */
    updateVisitsChart(data) {
        const chart = this.charts.get('visits');
        if (!chart) return;
        
        const option = {
            title: {
                show: false
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            legend: {
                data: ['访问量', '独立访客']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: data.dates
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '访问量',
                    type: 'line',
                    smooth: true,
                    data: data.visits,
                    itemStyle: {
                        color: '#5470c6'
                    }
                },
                {
                    name: '独立访客',
                    type: 'line',
                    smooth: true,
                    data: data.uniqueVisitors,
                    itemStyle: {
                        color: '#91cc75'
                    }
                }
            ]
        };
        
        chart.setOption(option);
    }

    /**
     * 更新页面分布图表
     */
    updatePagesChart(data) {
        const chart = this.charts.get('pages');
        if (!chart) return;
        
        const option = {
            title: {
                show: false
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '页面访问',
                    type: 'pie',
                    radius: '50%',
                    data: data.pages,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        
        chart.setOption(option);
    }

    /**
     * 切换图表类型
     */
    switchChartType(chartId, chartType) {
        const chart = this.charts.get(chartId === 'visitsChart' ? 'visits' : 'pages');
        if (!chart) return;
        
        if (chartId === 'visitsChart') {
            // 切换访问趋势图表类型
            const option = chart.getOption();
            
            if (chartType === 'bar') {
                option.series[0].type = 'bar';
                option.series[1].type = 'bar';
            } else {
                option.series[0].type = 'line';
                option.series[1].type = 'line';
            }
            
            chart.setOption(option);
        } else if (chartId === 'pagesChart') {
            // 切换页面分布图表类型
            const option = chart.getOption();
            
            if (chartType === 'donut') {
                option.series[0].radius = ['40%', '70%'];
            } else {
                option.series[0].radius = '50%';
            }
            
            chart.setOption(option);
        }
    }

    /**
     * 刷新数据
     */
    async refreshData() {
        // 添加旋转动画
        const refreshBtn = this.find('#refreshBtn');
        const icon = refreshBtn.querySelector('i');
        icon.classList.add('fa-spin');
        
        try {
            await this.loadData();
        } finally {
            // 移除旋转动画
            icon.classList.remove('fa-spin');
        }
    }

    /**
     * 启动实时更新
     */
    startRealTimeUpdates() {
        // 每30秒更新一次数据
        this.realTimeInterval = setInterval(() => {
            this.loadRealTimeActivity();
        }, 30000);
        
        // 立即加载一次
        this.loadRealTimeActivity();
    }

    /**
     * 停止实时更新
     */
    stopRealTimeUpdates() {
        if (this.realTimeInterval) {
            clearInterval(this.realTimeInterval);
            this.realTimeInterval = null;
        }
    }

    /**
     * 加载实时活动
     */
    async loadRealTimeActivity() {
        try {
            const response = await apiClient.get('/analytics/realtime-activity');
            this.updateActivityList(response.data);
        } catch (error) {
            console.error('Failed to load real-time activity:', error);
        }
    }

    /**
     * 更新活动列表
     */
    updateActivityList(activities) {
        const activityList = this.find('#activityList');
        
        // 清空现有列表
        activityList.innerHTML = '';
        
        // 添加新活动
        activities.forEach(activity => {
            const activityItem = document.createElement('div');
            activityItem.className = 'activity-item';
            
            const iconClass = this.getActivityIcon(activity.type);
            const timeAgo = this.getTimeAgo(activity.timestamp);
            
            activityItem.innerHTML = `
                <div class="activity-icon">
                    <i class="${iconClass}"></i>
                </div>
                <div class="activity-content">
                    <div class="activity-text">${activity.text}</div>
                    <div class="activity-time">${timeAgo}</div>
                </div>
            `;
            
            activityList.appendChild(activityItem);
        });
    }

    /**
     * 获取活动图标
     */
    getActivityIcon(type) {
        const iconMap = {
            'user_register': 'fas fa-user-plus',
            'user_login': 'fas fa-sign-in-alt',
            'page_view': 'fas fa-eye',
            'form_submit': 'fas fa-paper-plane',
            'purchase': 'fas fa-shopping-cart'
        };
        
        return iconMap[type] || 'fas fa-info-circle';
    }

    /**
     * 获取相对时间
     */
    getTimeAgo(timestamp) {
        const now = new Date();
        const time = new Date(timestamp);
        const diff = Math.floor((now - time) / 1000); // 秒
        
        if (diff < 60) {
            return '刚刚';
        } else if (diff < 3600) {
            return `${Math.floor(diff / 60)}分钟前`;
        } else if (diff < 86400) {
            return `${Math.floor(diff / 3600)}小时前`;
        } else {
            return `${Math.floor(diff / 86400)}天前`;
        }
    }

    /**
     * 格式化变化值
     */
    formatChange(change) {
        if (change > 0) {
            return `+${change}%`;
        } else if (change < 0) {
            return `${change}%`;
        } else {
            return '0%';
        }
    }

    /**
     * 更新变化指示器
     */
    updateChangeIndicator(element, change) {
        element.classList.remove('positive', 'negative', 'neutral');
        
        if (change > 0) {
            element.classList.add('positive');
        } else if (change < 0) {
            element.classList.add('negative');
        } else {
            element.classList.add('neutral');
        }
    }

    /**
     * 格式化持续时间
     */
    formatDuration(seconds) {
        if (seconds < 60) {
            return `${seconds}秒`;
        } else if (seconds < 3600) {
            return `${Math.floor(seconds / 60)}分钟`;
        } else {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            return `${hours}小时${minutes}分钟`;
        }
    }

    /**
     * 显示错误消息
     */
    showError(message) {
        // 创建错误元素
        const errorElement = document.createElement('div');
        errorElement.className = 'alert alert-danger';
        errorElement.textContent = message;
        
        // 插入到仪表盘顶部
        const dashboard = this.find('.dashboard');
        dashboard.insertBefore(errorElement, dashboard.firstChild);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (errorElement.parentNode) {
                errorElement.parentNode.removeChild(errorElement);
            }
        }, 3000);
    }

    /**
     * 销毁图表
     */
    destroyCharts() {
        this.charts.forEach(chart => {
            chart.dispose();
        });
        this.charts.clear();
    }
}

export default EnhancedDashboard;